package com.ethan.cj.ssm.util;

import org.springframework.data.redis.connection.DefaultedRedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

public class RedisUtil {
    private static JedisConnectionFactory connectionFactory;

    public static void set(Object key, Object value) {
        domain(jedis -> jedis.getJedis().set(serialize(key), serialize(value)));
    }

    public static Object get(Object key) {
        return domain(jedis -> deserialize(jedis.getJedis().get(serialize(key))));
    }

    public static void expire(Object key) {
        domain(jedis -> jedis.getJedis().expire(serialize(key), 0));
    }

    public static void flushDb() {
        domain(jedis -> jedis.getJedis().flushDB());
    }

    public static Long dbSize() {
        return domain(jedis -> jedis.getJedis().dbSize());
    }

    public static void setConnectionFactory(JedisConnectionFactory connectionFactory) {
        RedisUtil.connectionFactory = connectionFactory;
    }

    private static byte[] serialize(Object o) {
        RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
        return serializer.serialize(o);
    }

    private static Object deserialize(byte[] o) {
        RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
        return serializer.deserialize(o);
    }

    private interface RedisDomainInterface<T> {
        T domain(JedisConnection jedis);
    }

    private static <T> T domain(RedisDomainInterface<T> interfaces) {
        T Object;
        JedisConnection jedisConnection = (JedisConnection) connectionFactory.getConnection();
        try {
            Object = interfaces.domain(jedisConnection);
        } finally {
            jedisConnection.close();
        }
        return Object;
    }
}
